import { ref } from 'vue';
import { useMessageStore } from '@/store/message.js';
import {useSSE} from '@/utils/useSSE.js'

export function useSseService() {
    const messageStore = useMessageStore();
    const { eventData, error, isConnected, connect } = useSSE();
    const sseRequestTask = ref(null);
	const baseUrl = 'http://172.172.9.62:8091/service-sse';
    /**
     * 连接SSE服务
     * @param {number} phone - 用户ID
     * @param {string} identity - 用户身份
     * @param {string} baseUrl - 服务基础URL
     */
    const connectSSE = (phone, identity) => {
        error.value = null;
        
        // 关闭已存在的连接
        if (sseRequestTask.value) {
            sseRequestTask.value.abort();
        }
        
        sseRequestTask.value = connect(
            `${baseUrl}/connect`,
            { phone, identity },
            (data) => {
				console.log("消息：",data);
                if (data.trim() === '') return;
                
                if (data.includes('HEARTBEAT')) {
                    console.log("心跳机制");
                } else if (data.includes('SSE_CONNECTED')) {
                    console.log('SSE连接已建立');
                } else if (data.includes('SSE_CLOSED')) {
                    console.log('SSE连接已关闭');
                } else if (data.includes('Keep-alive')) {
                    return;
                } else {
                    // 处理业务消息
                    messageStore.setLatestMessage(data);
                    messageStore.addPushedMessage(data);
                    console.log('收到推送消息:', data);
                }
            }
        );
    };

    /**
     * 重连SSE服务
     * @param {number} phone - 用户ID
     * @param {string} identity - 用户身份
     * @param {string} baseUrl - 服务基础URL
     */
    const reconnectSSE = (phone, identity, baseUrl) => {
        if (isConnected.value) {
            uni.showToast({
                title: '已经建立连接，无需重连',
                icon: 'none',
                duration: 2000
            });
            return;
        }
        
        uni.showLoading({ title: '正在重连...' });
        connectSSE(phone, identity, baseUrl);
        
        setTimeout(() => {
            uni.hideLoading();
            if (!isConnected.value) {
                uni.showToast({
                    title: '重连失败，请检查网络',
                    icon: 'none',
                    duration: 2000
                });
            }
        }, 2000);
    };

    /**
     * 关闭SSE连接
     * @param {number} phone - 用户ID
     * @param {string} identity - 用户身份
     * @param {string} baseUrl - 服务基础URL
     */
    const closeSSE = (phone, identity) => {
        if (!sseRequestTask.value) return;
        
        uni.request({
            url: `${baseUrl}/close`,
            method: 'GET',
            data: { phone, identity },
            complete: () => {
                sseRequestTask.value.abort();
                sseRequestTask.value = null;
                isConnected.value = false;
                console.log('SSE 连接已关闭');
            }
        });
    };

    return {
        eventData,
        error,
        isConnected,
        connectSSE,
        reconnectSSE,
        closeSSE
    };
}